package cn.dream.ebag.MessengerLib.util;

import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.text.TextUtils;
import android.util.Log;

import java.util.ArrayList;

/**
 * @ProjectName: MessengerServer
 * @Package: cn.dream.mgclient.util
 * @Author: qktang
 * @CreateDate: 2021/1/13 19:53
 * @Description: 描述
 */
public class ServiceUtil {
    private static final String TAG = "ServiceUtil";


    public static boolean isServiceExitByAction(Context mContext, String action) {
        Intent intent = new Intent();
        intent.setAction(action);
        return isServiceExit(mContext, intent);
    }

    /**
     * 通过一个隐式的Intent获取可能会被启动的Service的信息
     * @param mContext
     * @param intent
     * @return
     */
    public static boolean isServiceExit(Context mContext, Intent intent) {
        PackageManager packageManager = mContext.getPackageManager();
        ResolveInfo resolveInfo = packageManager.resolveService(intent, 0);
        // //系统中有这个意图，说明我们能通过上面隐式的Intent找到对应的Service
        if (resolveInfo != null) {
            //得到的Service的包名
            String packageName = resolveInfo.serviceInfo.packageName;
            //得到的Service的类名
            String name = resolveInfo.serviceInfo.name;
            Log.d(TAG, "isServiceExit: pkg=" + packageName + ",serviceClassName=" + name);
            return true;
        }
        return false;
    }

    /**
     * 服务是否正在运行
     * @param mContext
     * @param cmpName
     * @return
     */
    private boolean checkIsServiceRunning(Context mContext, String cmpName) {
        if (mContext == null || TextUtils.isEmpty(cmpName)) {
            return false;
        }
        // 先判断service是否运行
        ActivityManager am = (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
        ArrayList<ActivityManager.RunningServiceInfo> runningServiceInfos = (ArrayList<ActivityManager.RunningServiceInfo>) am.getRunningServices(100);
        // maxNum要足够大才行 前30根本不够用
        for (int i = 0; i < runningServiceInfos.size(); i++) {
            if (runningServiceInfos.get(i).service.getClassName().toString().equals(cmpName)) {
                return true;
            }
        }
        return false;
    }

}
